package com.wsjzzcbq.util;

import com.wsjzzcbq.constant.MsgConsts;
import lombok.extern.slf4j.Slf4j;
import javax.swing.*;
import java.io.*;
import java.nio.file.Files;
import java.util.concurrent.*;

/**
 * FileTools 文件工具类
 *
 * @author wsjz
 * @date 2021/09/26
 */
@Slf4j
public class FileUtils {

    /**
     * 删除文件夹（文件夹下全部文件）或文件
     * @param filePath
     */
    public static void delete(String filePath) {
        File file = new File(filePath);
        delete(file);
    }

    public static void delete(File file) {
        deleteDir(file);
    }

    public static void delete(String filePath, JTextArea textArea, JTextField textField) {
        long start = System.currentTimeMillis();
        File file = new File(filePath);
        //根据文件数量判断，如果文件数>cpu核心数用多线程，小于cpu核心数用单线程
        if (file.isFile() || file.listFiles().length < SysUtils.processors()) {
            delete(file, textArea);
        } else {
            parallelDelete(file, textArea);
            //删除file文件目录
            delete(file, textArea);
        }

        long end = System.currentTimeMillis();
        double time = ((double)(end - start)) / 1000;
        textField.setText(String.valueOf(time) + MsgConsts.SECOND);
    }

    public static void delete(File file, JTextArea textArea) {
        deleteDir(file, textArea);
    }

    private static void deleteDir(File file, JTextArea textArea) {
        if(file.isFile()) {
            System.out.println("删除文件:" + file.getName());
            //更新UI
            SwingUtilities.invokeLater(()->textArea.append(MsgConsts.getDeleteFileMsg(file.getName())));

            file.delete();
            return;
        }

        if (file.isDirectory()) {
            try {
                for (File f : file.listFiles()) {
                    deleteDir(f, textArea);
                }
            } catch (Exception e) {
                log.error(file.getName() + ":" + e.getMessage(), e);
            }
            System.out.println("删除文件:" + file.getName());
            SwingUtilities.invokeLater(()->textArea.append(MsgConsts.getDeleteDirectoryMsg(file.getName())));
            file.delete();
            return;
        }

        if (Files.isSymbolicLink(file.toPath())) {
            System.out.println("删除快捷方式:" + file.getName());
            SwingUtilities.invokeLater(()->textArea.append(MsgConsts.getDeleteShortcutsMsg(file.getName())));
            file.delete();
            return;
        }

        System.out.println("删除文件:" + file.getName());
        SwingUtilities.invokeLater(()->textArea.append(MsgConsts.getDeleteDirectoryMsg(file.getName())));
        file.delete();
    }

    private static void deleteDir(File file) {
        if(file.isFile()) {
            System.out.println("删除文件:" + file.getName());
            file.delete();

        } else {
            for (File f : file.listFiles()) {
                deleteDir(f);
            }
            System.out.println("删除文件:" + file.getName());
            file.delete();
        }
    }

    /**
     * 获取文件类型
     * @param file
     * @return
     */
    public static String getFileType(String file) {
        return file.substring(file.lastIndexOf("."));
    }

    /**
     * 获取文件名（不带类型）
     * @param file
     * @return
     */
    public static String getFileName(String file) {
        return file.substring(0, file.lastIndexOf("."));
    }

    /**
     * 多线程删除
     * @param file
     */
    public static void parallelDelete(File file) {
        parallelDelete(file, null);
    }

    public static void parallelDelete(File file, JTextArea textArea) {
        CountDownLatch countDownLatch = new CountDownLatch(file.listFiles().length);
        int processors = SysUtils.processors();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(processors, processors,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>());

        for (File f : file.listFiles()) {
            threadPoolExecutor.execute(()->{
                if (textArea != null) {
                    delete(f, textArea);
                } else {
                    delete(f);
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
            System.out.println("完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadPoolExecutor.shutdown();
        //file.delete();
    }

//    public static void main(String[] args) {
//        //parallelDelete(new File("E:\\web-simple\\wsjz-exam-web\\node_modules\\.cache\\vue-loader"));
//
//        String f = "E:\\senyue\\web-project\\finance\\node_modules\\_@babel_template@7.0.0-beta.44@@babel\\template\\node_modules";
//        File file = new File(f);
//        for (File file1 : file.listFiles()) {
//            System.out.println(file1);
//            System.out.println(file1.isFile());
//            System.out.println(file1.isDirectory());
//            System.out.println(file1.isHidden());
//            System.out.println(Files.isSymbolicLink(file1.toPath()));
//            //Files.createLink()
//        }
//
//    }



}
